package daily.may0522;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    //重写equals和hashCode方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }
    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }
}
public class CustomizeMapTest {
    public static void main(String[] args) {
        //创建HashMap集合，将String类型作为键类型
        //String类内部已经重写了hashCode方法和equals方法,以保证key唯一
        HashMap<String,Person> map1 = new HashMap<>();
        //往集合中添加元素
        map1.put("北京",new Person("张三",18));
        map1.put("上海",new Person("李四",19));
        map1.put("广州",new Person("王五",20));
        //这里key值重复，应该将赵六替换张三
        map1.put("北京",new Person("赵六",18));
        //使用keySet加增强for遍历Map集合
        Set<String> set1 = map1.keySet();
        for (String key : set1) {
            Person value = map1.get(key);
            System.out.println(key+"-->"+value);
            //输出：
            //上海-->Person{name='李四', age=19}
            //广州-->Person{name='王五', age=20}
            //北京-->Person{name='赵六', age=18}
        }

        //创建HashMap集合，将Person类型作为键类型
        //Person类必须重写hashCode方法和equals方法,以保证key唯一
        HashMap<Person,String> map2 = new HashMap<>();
        //往集合中添加元素
        map2.put(new Person("女王",18),"英国");
        map2.put(new Person("秦始皇",18),"秦国");
        map2.put(new Person("普京",30),"俄罗斯");
        map2.put(new Person("女王",18),"毛里求斯");
        //使用entrySet和增强for遍历Map集合
        Set<Map.Entry<Person, String>> set2 = map2.entrySet();
        for (Map.Entry<Person, String> entry : set2) {
            Person key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"-->"+value);
            //输出：
            //Person{name='女王', age=18}-->毛里求斯
            //Person{name='秦始皇', age=18}-->秦国
            //Person{name='普京', age=30}-->俄罗斯
        }
    }
}
